package com.s63.appinfo.service.impl;

import com.s63.appinfo.mapper.AppInfoMapper;
import com.s63.appinfo.mapper.AppVersionMapper;
import com.s63.appinfo.pojo.AppInfo;
import com.s63.appinfo.pojo.AppVersion;
import com.s63.appinfo.service.AppInfoService;
import com.s63.appinfo.util.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AppInfoServiceImpl implements AppInfoService {
    @Autowired
    private AppInfoMapper appInfoMapper;
    @Autowired
    private AppVersionMapper appVersionMapper;

    @Override
    public List<AppInfo> get(AppInfo appInfo) {
        return appInfoMapper.select(appInfo);
    }

    @Override
    public int add(AppInfo appInfo) {
        appInfo.setStatus(1L);
        return appInfoMapper.insert(appInfo);
    }

    @Override
    public AppInfo getByApkName(String apkName) {
        return appInfoMapper.selectByApkName(apkName);
    }

    /**
     * 删除appinfo对应的version
     * 删除appinfo
     * @param id
     * @return
     */
    @Override
    @Transactional
    public boolean del(Long id) {
        // 删除版本
        List<AppVersion> appVersions = appVersionMapper.selectByAppId(id);
        for (AppVersion appVersion : appVersions) {
            FileUtils.delFile(appVersion.getApkFileName());
        }
        appVersionMapper.deleteByAppId(id);
        // 删除appinfo
        AppInfo appInfo = appInfoMapper.selectByPrimaryKey(id);
        FileUtils.delFile(appInfo.getLogoPicPath());
        return appInfoMapper.deleteByPrimaryKey(id) == 1;
    }

    @Override
    public AppInfo getById(Long id) {
        return appInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public boolean update(AppInfo appInfo) {
        return appInfoMapper.updateByPrimaryKeySelective(appInfo) > 0;
    }

}
